﻿package com.agileai.miscdp.hotweb.generator.mastersub;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;

import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.mastersub.MasterSubFuncModel;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.util.StringUtil;

import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
/**
 * JSP代码生成器
 */
public class MSJspPagGenerator implements Generator{
	private String template = null;
	private String listJspFile = null;
	private List<String> boxJspFileList = new ArrayList<String>();
	private List<String> boxSubTabIdList = new ArrayList<String>();
	private String detailJspFile = null;
	private File xmlFile = null;
	private String charencoding = "UTF-8";
	private String templateDir = null;
	private MasterSubFuncModel funcModel = null;
	
	public void generate() {
		String fileName = "template";
		try {
			templateDir = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(fileName)).getFile().toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		generateList();
		generateDetail();
		generateBoxJspList();
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void generateList() {
        try {
        	Configuration cfg = new Configuration();
        	cfg.setDirectoryForTemplateLoading(new File(templateDir));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            cfg.setEncoding(Locale.getDefault(), charencoding);
            String templateFile = "/mastersub/ListPage.jsp.ftl";
        	Template temp = cfg.getTemplate(templateFile);
        	temp.setEncoding(charencoding);
            Map root = new HashMap();
            NodeModel nodeModel = freemarker.ext.dom.NodeModel.parse(xmlFile);
            root.put("doc",nodeModel);
            File file = new File(listJspFile);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()){
            	parentFile.mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),charencoding));
//            Writer out = new OutputStreamWriter(System.out);
            temp.process(root, out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }		
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void generateDetail() {
        try {
        	Configuration cfg = new Configuration();  	
        	cfg.setDirectoryForTemplateLoading(new File(templateDir));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            cfg.setEncoding(Locale.getDefault(),charencoding);
        	String templateFile = "/mastersub/";
        	if (MasterSubFuncModel.TEMPLATE_BASETABED.equals(this.template)){
        		templateFile = templateFile+"EditMainPage_Tabed.jsp.ftl";
        	}
        	else if (MasterSubFuncModel.TEMPLATE_BASETOPED.equals(this.template)){
        		templateFile = templateFile+"EditMainPage_Toped.jsp.ftl";
        	}
        	Template temp = cfg.getTemplate(templateFile);
        	temp.setEncoding(charencoding);
            Map root = new HashMap();
            NodeModel nodeModel = freemarker.ext.dom.NodeModel.parse(xmlFile);
            root.put("doc",nodeModel);
			String uniqueFieldCode = funcModel.retrieveUniqueField(funcModel.getPageFormFields());
			boolean checkUnique = !StringUtil.isNullOrEmpty(uniqueFieldCode);
            root.put("checkUnique", checkUnique);
            File file = new File(this.detailJspFile);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()){
            	parentFile.mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),charencoding));
//            Writer out = new OutputStreamWriter(System.out);
            temp.process(root, out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }		
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void generateBoxJspList() {
        try {
        	if (!this.boxJspFileList.isEmpty()){
            	for (int i=0;i < this.boxJspFileList.size();i++){
                	Configuration cfg = new Configuration();  	
                	cfg.setDirectoryForTemplateLoading(new File(templateDir));
                    cfg.setObjectWrapper(new DefaultObjectWrapper());
                    cfg.setEncoding(Locale.getDefault(),charencoding);
                	String templateFile = "/mastersub/";
                	templateFile = templateFile+"EditPboxPage.jsp.ftl";
                	Template temp = cfg.getTemplate(templateFile);
                	temp.setEncoding(charencoding);
            		String boxJspFile = this.boxJspFileList.get(i);
                    Map root = new HashMap();
                    NodeModel nodeModel = freemarker.ext.dom.NodeModel.parse(xmlFile);
                    root.put("doc",nodeModel);
                    root.put("currentEntryEditTableIndex",i);
                    String subTableId = this.boxSubTabIdList.get(i);
                    List<PageFormField> paramFields = funcModel.getSubPboxFormFields(subTableId);
        			String uniqueFieldCode = funcModel.retrieveUniqueField(paramFields);
        			boolean checkUnique = !StringUtil.isNullOrEmpty(uniqueFieldCode);
                    root.put("checkUnique", checkUnique);
                    File file = new File(boxJspFile);
                    File parentFile = file.getParentFile();
                    if (!parentFile.exists()){
                    	parentFile.mkdirs();
                    }
                    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),charencoding));
//                    Writer out = new OutputStreamWriter(System.out);
                    temp.process(root, out);
                    out.flush();
            	}
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }		
	}
	
	
	public String getListJspFile() {
		return listJspFile;
	}

	public void setListJspFile(String xmlFile) {
		this.listJspFile = xmlFile;
	}

	public String getDetailJspFile() {
		return detailJspFile;
	}

	public void setDetailJspFile(String detailJspFile) {
		this.detailJspFile = detailJspFile;
	}
	
	public File getXmlFile() {
		return xmlFile;
	}
	
	public void setXmlFile(File xmlFile) {
		this.xmlFile = xmlFile;
	}
	
	public void setTemplate(String template) {
		this.template = template;
	}
	
	public List<String> getBoxJspFileList() {
		return boxJspFileList;
	}
	
	public void setFuncModel(MasterSubFuncModel funcModel) {
		this.funcModel = funcModel;
	}
	
	public List<String> getBoxSubTabIdList() {
		return boxSubTabIdList;
	}
}